package service

import (
	"BlazeRider-backend/app/manager"
	"BlazeRider-backend/app/models"
	"BlazeRider-backend/app/utils"
	"database/sql"
	"fmt"
	"github.com/google/uuid"
	"github.com/gorilla/websocket"
	"strconv"
	"time"
)

type LiveRoomService struct{}

func (ls LiveRoomService) OneUserJoinTrack(liveRoomID string, userId string, nickName string, avatarUrl string, track int, job int) error {
	var liveRoomInfo *manager.LiveRoomInfo
	liveRoomInfo, err := manager.Get().LiveRoomManager().GetLiveInfo(liveRoomID)
	if err != nil {
		//return fmt.Errorf("want join track but get live info error: %v, by no live room", err)
		liveRoomInfo = &manager.LiveRoomInfo{
			State: "start",
			Times: 1,
		}
		fmt.Println("触发直播间不存在的时候，给抖音做的专门的直播间初始化，live_room_id : ", liveRoomID)
	}

	// 用户不存在时进行初始化（示例值）
	if err := manager.Get().UserManager().InitializeUser(
		userId,
		nickName,
		avatarUrl,
		1, // 初始等级
	); err != nil {

	}

	err = manager.Get().LiveRoomManager().JoinLiveRoomCamp(liveRoomID, liveRoomInfo.Times, liveRoomInfo.State, userId, track, job)

	if err != nil {
		return err
	}

	// 获取当前时间
	now := time.Now()

	userName := ""
	userHeadImg := ""
	level := 0
	UserScore := 0
	//userInfo, err := i.userManager.GetUser(userId)
	userInfo, err := manager.Get().UserManager().GetUser(userId)
	if err == nil {
		userName = userInfo.UserName
		userHeadImg = userInfo.HeadImg
		level = userInfo.Level
		UserScore = userInfo.Score
	}

	if liveRoomID != utils.TestRoomId {
		err := DouYinService{}.SyncUserGroupToDouYinService(liveRoomID, liveRoomInfo.Times, string(track), userId)
		if err != nil {
			fmt.Println("sync user group status end to dou yin err : ", err, ", room id : ", liveRoomID)
		}
	}

	// 创建一个礼物事件
	data := models.LiveEventData{
		Event: "broad_join_track",
		Data: struct {
			MsgID         string `json:"msg_id"`         // 事件的ID
			SecOpenID     string `json:"sec_openid"`     // 用户的加密openid
			Type          string `json:"type"`           // 事件类型：comment, gift, like
			Content       string `json:"content"`        // 评论内容（仅评论有效）
			Camp          int    `json:"camp"`           // 评论内容（仅评论有效）
			Job           int    `json:"job"`            // 所属职业
			SecGiftID     string `json:"sec_gift_id"`    // 加密的礼物id（仅礼物有效）
			GiftNum       int    `json:"gift_num"`       // 送出的礼物数量（仅礼物有效）
			GiftValue     int    `json:"gift_value"`     // 礼物总价值，单位分（仅礼物有效）
			Name          string `json:"name"`           // 用户昵称
			Level         int    `json:"level"`          // 用户等级
			AccGiftScore  int    `json:"acc_gift_score"` // 直播间当前用户累计礼物价值
			LikeNum       string `json:"like_num"`       // 点赞数量（仅点赞有效）
			AvatarURL     string `json:"avatar_url"`     // 用户头像
			Nickname      string `json:"nickname"`       // 用户昵称
			UserScore     int    `json:"user_score"`     // 用户积分
			GiftLevel     int    `json:"gift_level"`     // 礼物等级
			GiftUpgrading int    `json:"gift_upgrading"` // 礼物当前次升级
			GameScore     int    `json:"game_score"`     // 游戏当局分数
			Timestamp     int64  `json:"timestamp"`      // 事件时间戳
		}{
			MsgID:     uuid.New().String(),
			SecOpenID: userId,
			Type:      "broad_join_track",
			Content:   strconv.Itoa(track),
			Camp:      track,
			Job:       job,
			SecGiftID: "n1/Dg1905sj1FyoBlQBvmbaDZFBNaKuKZH6zxHkv8Lg5x2cRfrKUTb8gzMs=",
			GiftNum:   2,
			GiftValue: 10,
			Name:      "",
			Nickname:  userName,
			Level:     level,
			AvatarURL: userHeadImg,
			UserScore: UserScore,
			Timestamp: now.UnixMilli(),
		},
	}

	manager.Get().EventManager().AddEventData(liveRoomID, data)
	return nil
}

func (ls LiveRoomService) SendTestPingLunNoStoage(liveRoomID string, userId, userName, userHeadImg string, track int) error {
	now := time.Now()
	// 创建一个礼物事件
	data := models.LiveEventData{
		Event: "broad_join_track",
		Data: struct {
			MsgID         string `json:"msg_id"`         // 事件的ID
			SecOpenID     string `json:"sec_openid"`     // 用户的加密openid
			Type          string `json:"type"`           // 事件类型：comment, gift, like
			Content       string `json:"content"`        // 评论内容（仅评论有效）
			Camp          int    `json:"camp"`           // 评论内容（仅评论有效）
			Job           int    `json:"job"`            // 所属职业
			SecGiftID     string `json:"sec_gift_id"`    // 加密的礼物id（仅礼物有效）
			GiftNum       int    `json:"gift_num"`       // 送出的礼物数量（仅礼物有效）
			GiftValue     int    `json:"gift_value"`     // 礼物总价值，单位分（仅礼物有效）
			Name          string `json:"name"`           // 用户昵称
			Level         int    `json:"level"`          // 用户等级
			AccGiftScore  int    `json:"acc_gift_score"` // 直播间当前用户累计礼物价值
			LikeNum       string `json:"like_num"`       // 点赞数量（仅点赞有效）
			AvatarURL     string `json:"avatar_url"`     // 用户头像
			Nickname      string `json:"nickname"`       // 用户昵称
			UserScore     int    `json:"user_score"`     // 用户积分
			GiftLevel     int    `json:"gift_level"`     // 礼物等级
			GiftUpgrading int    `json:"gift_upgrading"` // 礼物当前次升级
			GameScore     int    `json:"game_score"`     // 游戏当局分数
			Timestamp     int64  `json:"timestamp"`      // 事件时间戳
		}{
			MsgID:     uuid.New().String(),
			SecOpenID: userId,
			Type:      "broad_join_track",
			Content:   strconv.Itoa(track),
			Camp:      track,
			Job:       0,
			SecGiftID: "n1/Dg1905sj1FyoBlQBvmbaDZFBNaKuKZH6zxHkv8Lg5x2cRfrKUTb8gzMs=",
			GiftNum:   2,
			GiftValue: 10,
			Name:      "",
			Nickname:  userName,
			Level:     1,
			AvatarURL: userHeadImg,
			UserScore: 123,
			Timestamp: now.UnixMilli(),
		},
	}

	//i.eventManager.AddEventData(liveRoomID, data)
	manager.Get().EventManager().AddEventData(liveRoomID, data)
	return nil
}

func (ls LiveRoomService) OneUserSendGift(msgID string, liveRoomID string, userId string, giftId string, giftNum int) error {
	// 1、获取直播间状态
	liveRoomInfo, err := manager.Get().LiveRoomManager().GetLiveInfo(liveRoomID)
	//liveStatus, hasErr := manager.Get().LiveRoomManager().GetLiveRoomStatus(liveRoomID)

	if err != nil {
		fmt.Println("error: can not find liveRoomID from liveRoomManager , err:", err)
		return fmt.Errorf("error: can not find liveRoomID from liveRoomManager, %v", err)
	}
	if liveRoomInfo.State != "start" {
		return fmt.Errorf("send gift error liveRoomId is not start")
	}

	userLiveTrack, err := manager.Get().LiveRoomManager().GetLiveTrackByUserId(liveRoomID, userId)
	if err != nil {
		userInfo, err := manager.Get().UserManager().GetUser(userId)
		if err != nil {
		}

		track, _ := utils.GetRandomTeamId()
		job, _ := utils.GetRandomJobId()

		ls.OneUserJoinTrack(liveRoomID, userId, userInfo.UserName, userInfo.HeadImg, track, job)
		fmt.Printf("用户id : %s, 暂未加入直播间: %s, 阵营却送了礼物，自动加入阵营: %d, 职业: %d",
			userId, liveRoomID, track, job)

		userLiveTrack, err = manager.Get().LiveRoomManager().GetLiveTrackByUserId(liveRoomID, userId)
	}

	track := userLiveTrack.Track
	job := userLiveTrack.Job

	// 计算礼物是否可以升级
	giftLevel := 1
	giftUpgrading := 0

	giftInfo, err := manager.Get().GiftManager().GetGiftByID(giftId)
	if err != nil {
		return fmt.Errorf("can not find gift by giftId , err : %v", err)
	}

	giftName := giftInfo.Name
	giftValue := giftInfo.Value
	giftScore := giftInfo.Score

	// 查询本局最后一次该礼物信息
	giftLastRecord, err := manager.Get().GiftRecordManager().GetLastGiftRecordByUserIdAndGiftId(liveRoomID, liveRoomInfo.Times, userId, giftId)
	// 如果没有数据，则此次插入不做升级处理
	if err != nil {

	} else if giftLastRecord.GiftLevel == 2 {
		giftLevel = 2
	}

	// 如果msgId对应的礼物记录已经插入，则跳过
	giftRecord, err := manager.Get().GiftRecordManager().GetGiftRecordByMsgId(msgID)
	if giftRecord != nil {
		return fmt.Errorf("gift record with msgId is there now error : %v", err)
	}

	// 如果没有该礼物，或礼物的grade是1，则插入数据，礼物等级1，
	// 如果礼物等级是2，则直接插入礼物等级是2的数据
	err = manager.Get().GiftRecordManager().AddGiftRecord(msgID, liveRoomID, userId, giftId, giftName,
		giftValue, giftScore, giftNum, liveRoomInfo.Times, giftLevel, giftUpgrading, track, job)

	if err != nil {
		return fmt.Errorf("add gift record error : %v", err)
	}

	// 如果礼物的grade是1，而且查询总数超过礼物limit的量，则给本次的礼物记录根据msgId升级到2
	if giftLevel == 1 {
		gameTotalNum, err := manager.Get().GiftRecordManager().GetGiftCountByUserAndGiftId(liveRoomID,
			liveRoomInfo.Times, userId, giftId)
		if err != nil {
			return fmt.Errorf("get gift count by user and giftId err : %v", err)
		}
		if gameTotalNum >= giftInfo.UpgradeLimit {
			giftLevel = 2
			giftUpgrading = 1
			err := manager.Get().GiftRecordManager().SetGiftRecordLevel(msgID, giftLevel, giftUpgrading)
			if err != nil {
				return fmt.Errorf("set Gift Record Level err : %v", err)
			}
		}
	}

	// 创建广播礼物数据
	now := time.Now()

	userName := ""
	userHeadImg := ""
	level := 0
	userScore := 0
	userInfo, err := manager.Get().UserManager().GetUser(userId)
	if err == nil {
		userName = userInfo.UserName
		userHeadImg = userInfo.HeadImg
		level = userInfo.Level
		userScore = userInfo.Score
	}

	gameScore, _ := manager.Get().GiftRecordManager().GetTotalScoreByRoomId(liveRoomID, liveRoomInfo.Times)

	accScore, _ := manager.Get().GiftRecordManager().GetAccScoreByRoomIdAndUserId(liveRoomID, liveRoomInfo.Times, userId)

	// 创建一个礼物事件
	data := models.LiveEventData{
		Event: "broad_live_gift",
		Data: struct {
			MsgID         string `json:"msg_id"`         // 事件的ID
			SecOpenID     string `json:"sec_openid"`     // 用户的加密openid
			Type          string `json:"type"`           // 事件类型：comment, gift, like
			Content       string `json:"content"`        // 评论内容（仅评论有效）
			Camp          int    `json:"camp"`           // 所属阵营
			Job           int    `json:"job"`            // 所属职业
			SecGiftID     string `json:"sec_gift_id"`    // 加密的礼物id（仅礼物有效）
			GiftNum       int    `json:"gift_num"`       // 送出的礼物数量（仅礼物有效）
			GiftValue     int    `json:"gift_value"`     // 礼物总价值，单位分（仅礼物有效）
			Name          string `json:"name"`           // 用户昵称
			Level         int    `json:"level"`          // 用户等级
			AccGiftScore  int    `json:"acc_gift_score"` // 直播间当前用户累计礼物价值
			LikeNum       string `json:"like_num"`       // 点赞数量（仅点赞有效）
			AvatarURL     string `json:"avatar_url"`     // 用户头像
			Nickname      string `json:"nickname"`       // 用户昵称
			UserScore     int    `json:"user_score"`     // 用户积分
			GiftLevel     int    `json:"gift_level"`     // 礼物等级
			GiftUpgrading int    `json:"gift_upgrading"` // 礼物当前次升级
			GameScore     int    `json:"game_score"`     // 游戏当局分数
			Timestamp     int64  `json:"timestamp"`      // 事件时间戳
		}{
			MsgID:         uuid.New().String(),
			SecOpenID:     userId,
			Type:          "live_gift",
			Camp:          track,
			Job:           job,
			SecGiftID:     giftId,
			GiftNum:       giftNum,
			GiftValue:     giftValue * giftNum,
			Name:          giftName,
			Nickname:      userName,
			Level:         level,
			AccGiftScore:  accScore,
			AvatarURL:     userHeadImg,
			UserScore:     userScore,
			GiftLevel:     giftLevel,
			GiftUpgrading: giftUpgrading,
			GameScore:     gameScore,
			Timestamp:     now.UnixMilli(),
		},
	}

	//i.eventManager.AddEventData(liveRoomID, data)
	manager.Get().EventManager().AddEventData(liveRoomID, data)
	fmt.Println(liveRoomID, "号直播间，收货礼物广播事件 已 add")
	return nil
}

func (ls LiveRoomService) SendTestGiftNoStoage(liveRoomID string, userId, userName, userHeadImg string, giftId string, giftNum int, track, accGiftScore int) error {

	now := time.Now()

	giftInfo, err := manager.Get().GiftManager().GetGiftByID(giftId)
	if err != nil {
		return fmt.Errorf("can not find gift by giftId , err : %v", err)
	}

	giftName := giftInfo.Name
	giftValue := giftInfo.Value
	giftScore := giftInfo.Score

	// 创建一个礼物事件
	data := models.LiveEventData{
		Event: "broad_live_gift",
		Data: struct {
			MsgID         string `json:"msg_id"`         // 事件的ID
			SecOpenID     string `json:"sec_openid"`     // 用户的加密openid
			Type          string `json:"type"`           // 事件类型：comment, gift, like
			Content       string `json:"content"`        // 评论内容（仅评论有效）
			Camp          int    `json:"camp"`           // 所属阵营
			Job           int    `json:"job"`            // 所属职业
			SecGiftID     string `json:"sec_gift_id"`    // 加密的礼物id（仅礼物有效）
			GiftNum       int    `json:"gift_num"`       // 送出的礼物数量（仅礼物有效）
			GiftValue     int    `json:"gift_value"`     // 礼物总价值，单位分（仅礼物有效）
			Name          string `json:"name"`           // 用户昵称
			Level         int    `json:"level"`          // 用户等级
			AccGiftScore  int    `json:"acc_gift_score"` // 直播间当前用户累计礼物价值
			LikeNum       string `json:"like_num"`       // 点赞数量（仅点赞有效）
			AvatarURL     string `json:"avatar_url"`     // 用户头像
			Nickname      string `json:"nickname"`       // 用户昵称
			UserScore     int    `json:"user_score"`     // 用户积分
			GiftLevel     int    `json:"gift_level"`     // 礼物等级
			GiftUpgrading int    `json:"gift_upgrading"` // 礼物当前次升级
			GameScore     int    `json:"game_score"`     // 游戏当局分数
			Timestamp     int64  `json:"timestamp"`      // 事件时间戳
		}{
			MsgID:         uuid.New().String(),
			SecOpenID:     userId,
			Type:          "live_gift",
			Camp:          track,
			SecGiftID:     giftId,
			GiftNum:       giftNum,
			GiftValue:     giftValue,
			Name:          giftName,
			Nickname:      userName,
			Level:         1,
			AccGiftScore:  accGiftScore,
			AvatarURL:     userHeadImg,
			UserScore:     giftScore,
			GiftLevel:     1,
			GiftUpgrading: 0,
			GameScore:     accGiftScore,
			Timestamp:     now.UnixMilli(),
		},
	}

	//i.eventManager.AddEventData(liveRoomID, data)
	manager.Get().EventManager().AddEventData(liveRoomID, data)
	fmt.Println(liveRoomID, "号直播间，收货礼物广播事件 已 add")
	return nil
}
func (ls LiveRoomService) FinishGame(msgID string, liveRoomId string, finishTrackInfos []models.FinishTrackInfo, timestamp int) ([]models.LiveRoomResult, error) {
	// 获取直播间信息
	liveRoomInfo, err := manager.Get().LiveRoomManager().GetLiveInfo(liveRoomId)
	if err != nil {
		fmt.Println("Error: cannot find liveRoomID from LiveRoomManager")
		return nil, fmt.Errorf("error: cannot find liveRoomID from LiveRoomManager")
	}

	// 如果直播间状态不是 "end"，更新直播间状态
	if liveRoomInfo.State != "end" {
		manager.Get().LiveRoomManager().SetLiveRoomStatus(liveRoomId, false)
	}

	liveRoomResult, err := manager.Get().LiveRoomManager().GetLiveRoomResults(liveRoomId, liveRoomInfo.Times)
	if err == nil {
		// 创建一个礼物事件
		data := models.LiveEventData{
			Event: "broad_end_game",
			Data: struct {
				MsgID         string `json:"msg_id"`         // 事件的ID
				SecOpenID     string `json:"sec_openid"`     // 用户的加密openid
				Type          string `json:"type"`           // 事件类型：comment, gift, like
				Content       string `json:"content"`        // 评论内容（仅评论有效）
				Camp          int    `json:"camp"`           // 所属阵营
				Job           int    `json:"job"`            // 所属职业
				SecGiftID     string `json:"sec_gift_id"`    // 加密的礼物id（仅礼物有效）
				GiftNum       int    `json:"gift_num"`       // 送出的礼物数量（仅礼物有效）
				GiftValue     int    `json:"gift_value"`     // 礼物总价值，单位分（仅礼物有效）
				Name          string `json:"name"`           // 用户昵称
				Level         int    `json:"level"`          // 用户等级
				AccGiftScore  int    `json:"acc_gift_score"` // 直播间当前用户累计礼物价值
				LikeNum       string `json:"like_num"`       // 点赞数量（仅点赞有效）
				AvatarURL     string `json:"avatar_url"`     // 用户头像
				Nickname      string `json:"nickname"`       // 用户昵称
				UserScore     int    `json:"user_score"`     // 用户积分
				GiftLevel     int    `json:"gift_level"`     // 礼物等级
				GiftUpgrading int    `json:"gift_upgrading"` // 礼物当前次升级
				GameScore     int    `json:"game_score"`     // 游戏当局分数
				Timestamp     int64  `json:"timestamp"`      // 事件时间戳
			}{
				MsgID:     uuid.New().String(),
				Type:      "broad_end_game",
				Name:      liveRoomId,
				Timestamp: time.Now().UnixMilli(),
			},
		}

		manager.Get().EventManager().AddEventData(liveRoomId, data)

		return liveRoomResult, nil
	}

	// 提取完成比赛的赛道和冠军赛道
	var finishTrackArr []int
	var championTrack int
	var highestTrack int
	highestDistance := float32(0)
	for index, info := range finishTrackInfos {
		fmt.Println(info, index)
		if info.IsFinish == 1 {
			finishTrackArr = append(finishTrackArr, info.Track)
			if highestDistance < info.JumpHeight {
				highestDistance = info.JumpHeight
				highestTrack = info.Track
			}
		}
		if info.IsChampion == 1 {
			championTrack = info.Track
		}
	}

	// 获取礼物记录
	giftRecordList, err := manager.Get().GiftRecordManager().GetGiftRecordWithUserInfoByLiveRoomAndTimes(liveRoomId, liveRoomInfo.Times)
	if err != nil {
		// 假设查询结果为空
		emptyResult := []models.LiveRoomResult{} // 显式初始化
		return emptyResult, nil
	}

	// 获取直播间当局比赛的全部积分
	liveRoomTotalScore, liveRoomChampionTrackTotalScore, liveRoomOtherFinishTrackTotalScore := 0, 0, 0
	type userScoreRecord struct {
		Value     int
		Score     int
		Track     int
		Job       int
		UserName  string
		HeadImg   string
		UserLevel int
		UserScore int
		ExpireAt  sql.NullTime
	}
	liveRoomUserScoreRecord := make(map[string]userScoreRecord)
	type trackBiggestRecord struct {
		BiggestScore int
		Track        int
		UserId       string
	}
	trackBiggestMap := make(map[int]trackBiggestRecord)
	for _, giftRecord := range giftRecordList {
		liveRoomTotalScore += giftRecord.TotalScore
		if championTrack == giftRecord.Track {
			liveRoomChampionTrackTotalScore += giftRecord.TotalScore
		} else if utils.Exists(finishTrackArr, giftRecord.Track) {
			liveRoomOtherFinishTrackTotalScore += giftRecord.TotalScore
		}
		// 将礼物记录记录到每个UserId的礼物积分总数
		if scoreRecord, exists := liveRoomUserScoreRecord[giftRecord.UserId]; exists {
			liveRoomUserScoreRecord[giftRecord.UserId] = userScoreRecord{
				Value:     scoreRecord.Value + giftRecord.TotalValue,
				Score:     scoreRecord.Score + giftRecord.TotalScore,
				Track:     giftRecord.Track,
				Job:       giftRecord.Job,
				UserName:  giftRecord.UserName,
				HeadImg:   giftRecord.UserHeadImg,
				UserLevel: giftRecord.UserLevel,
				UserScore: giftRecord.UserScore,
				ExpireAt:  giftRecord.ExpireAt,
			}
		} else {
			// 如果 userId 不存在，直接初始化 Score
			liveRoomUserScoreRecord[giftRecord.UserId] = userScoreRecord{
				Value:     giftRecord.TotalValue,
				Score:     giftRecord.TotalScore,
				Track:     giftRecord.Track,
				Job:       giftRecord.Job,
				UserName:  giftRecord.UserName,
				HeadImg:   giftRecord.UserHeadImg,
				UserLevel: giftRecord.UserLevel,
				UserScore: giftRecord.UserScore,
				ExpireAt:  giftRecord.ExpireAt,
			}
		}
	}

	// 找到每个阵营最大贡献的记录
	for userId, userScoreRecordInfo := range liveRoomUserScoreRecord {
		if trackBiggestInfo, exists := trackBiggestMap[userScoreRecordInfo.Track]; exists {
			if trackBiggestInfo.BiggestScore < userScoreRecordInfo.Score {
				trackBiggestMap[userScoreRecordInfo.Track] = trackBiggestRecord{
					BiggestScore: userScoreRecordInfo.Score,
					Track:        userScoreRecordInfo.Track,
					UserId:       userId,
				}
			}
		} else {
			// 如果 userId 不存在，直接初始化 Score
			trackBiggestMap[userScoreRecordInfo.Track] = trackBiggestRecord{
				BiggestScore: userScoreRecordInfo.Score,
				Track:        userScoreRecordInfo.Track,
				UserId:       userId,
			}
		}
	}

	// 分配积分
	if liveRoomTotalScore <= 0 {
		fmt.Println("No total score to distribute.")
		return nil, nil
	}

	totalParts := 4
	championShare := 3
	remainingShare := 1

	// 如果只有冠军完成，则全给冠军
	if len(finishTrackArr) == 1 {
		championShare = 4
		remainingShare = 0
	}

	partScore := liveRoomTotalScore / totalParts
	championScore := partScore * championShare   // 冠军队伍分得积分
	remainingScore := partScore * remainingShare //非冠军完成队伍分得积分

	results := []models.LiveRoomResult{}
	for userId, scoreRecord := range liveRoomUserScoreRecord {
		getScore := 0
		isFinish := 0
		isChampion := 0
		if scoreRecord.Track == championTrack {
			getScore = championScore * scoreRecord.Score / liveRoomChampionTrackTotalScore
			isFinish = 1
			isChampion = 1
		} else if utils.Exists(finishTrackArr, scoreRecord.Track) {
			getScore = remainingScore * scoreRecord.Score / liveRoomOtherFinishTrackTotalScore
			isFinish = 1
			isChampion = 0
		}
		isBiggest := 0
		if trackBiggestInfo, exists := trackBiggestMap[scoreRecord.Track]; exists {
			if trackBiggestInfo.UserId == userId {
				isBiggest = 1
			}
		}

		// 计算用户将获得的积分和等级
		targetScore := scoreRecord.UserScore + getScore
		targetLevelInfo, err := manager.Get().LevelManager().GetLevelInfoByUpperScore(targetScore)
		targetLevel := 1
		if err != nil {
			targetLevel = 1
		}
		targetLevel = targetLevelInfo.Level

		// 处理高度和里程
		mileage := 0
		jumpHeight := float32(0)
		finishTime := 0
		finishTime1 := 0
		finishTime2 := 0
		fastestSpeed := 0
		attackPower := 0
		for _, info := range finishTrackInfos {
			if scoreRecord.Track == info.Track {
				mileage = info.Mileage
				if info.GameMode == 1 || info.GameMode == 0 {
					finishTime = info.FinishTime
				} else if info.GameMode == 2 {
					finishTime1 = info.FinishTime
				} else if info.GameMode == 3 {
					finishTime2 = info.FinishTime
				}

				fastestSpeed = info.FastestSpeed
				attackPower = info.AttackPower
			}
		}
		if scoreRecord.Track == highestTrack {
			jumpHeight = highestDistance
		}

		results = append(results, models.LiveRoomResult{
			LiveRoomID:   liveRoomId,
			Times:        liveRoomInfo.Times,
			UserID:       userId,
			GameScore:    liveRoomTotalScore,
			Track:        scoreRecord.Track, // 需要根据实际情况设置
			Job:          scoreRecord.Job,   // 需要根据实际情况设置
			IsChampion:   isChampion,
			IsFinish:     isFinish,
			IsBiggest:    isBiggest,
			GiftValue:    scoreRecord.Value, // 需要根据实际情况设置
			GiftScore:    scoreRecord.Score,
			GetScore:     getScore,
			HasDone:      0,
			UserName:     scoreRecord.UserName,
			HeadImg:      scoreRecord.HeadImg,
			UserLevel:    scoreRecord.UserLevel,
			UserScore:    scoreRecord.UserScore,
			TargetLevel:  targetLevel,
			TargetScore:  targetScore,
			Mileage:      mileage,
			JumpHeight:   jumpHeight,
			FinishTime:   finishTime,
			FinishTime1:  finishTime1,
			FinishTime2:  finishTime2,
			FastestSpeed: fastestSpeed,
			AttackPower:  attackPower,
			ExpireAt: sql.NullTime{
				Time:  time.Now(),
				Valid: true,
			},
		})
	}

	// 处理找出每个track最大的值

	err = manager.Get().LiveRoomManager().BatchInsertLiveRoomResults(results)
	if err != nil {
		fmt.Println("Error: cannot find liveRoomID from LiveRoomManager : %v", err)
		return nil, fmt.Errorf("error: batch insert live room result err : %v", err)
	}

	// 创建一个礼物事件
	data := models.LiveEventData{
		Event: "broad_end_game",
		Data: struct {
			MsgID         string `json:"msg_id"`         // 事件的ID
			SecOpenID     string `json:"sec_openid"`     // 用户的加密openid
			Type          string `json:"type"`           // 事件类型：comment, gift, like
			Content       string `json:"content"`        // 评论内容（仅评论有效）
			Camp          int    `json:"camp"`           // 所属阵营
			Job           int    `json:"job"`            // 所属职业
			SecGiftID     string `json:"sec_gift_id"`    // 加密的礼物id（仅礼物有效）
			GiftNum       int    `json:"gift_num"`       // 送出的礼物数量（仅礼物有效）
			GiftValue     int    `json:"gift_value"`     // 礼物总价值，单位分（仅礼物有效）
			Name          string `json:"name"`           // 用户昵称
			Level         int    `json:"level"`          // 用户等级
			AccGiftScore  int    `json:"acc_gift_score"` // 直播间当前用户累计礼物价值
			LikeNum       string `json:"like_num"`       // 点赞数量（仅点赞有效）
			AvatarURL     string `json:"avatar_url"`     // 用户头像
			Nickname      string `json:"nickname"`       // 用户昵称
			UserScore     int    `json:"user_score"`     // 用户积分
			GiftLevel     int    `json:"gift_level"`     // 礼物等级
			GiftUpgrading int    `json:"gift_upgrading"` // 礼物当前次升级
			GameScore     int    `json:"game_score"`     // 游戏当局分数
			Timestamp     int64  `json:"timestamp"`      // 事件时间戳
		}{
			MsgID:     uuid.New().String(),
			Type:      "broad_end_game",
			Name:      liveRoomId,
			Timestamp: time.Now().UnixMilli(),
		},
	}

	manager.Get().EventManager().AddEventData(liveRoomId, data)

	go DealUserLiveRoomResultScoreToUser()

	return results, nil
}

// 处理升级，并送礼物
func DealUserLiveRoomResultScoreToUser() error {
	err := manager.Get().UserManager().SetUserScoreByLiveRoomResult()
	if err != nil {
		fmt.Println("Error: cannot not SetUserScoreByLiveRoomResult : %v", err)
	}

	timeStr := time.Now().Format("2006-01-02 15:04:05")

	levelSets, err := manager.Get().LevelManager().GetLevelSets()
	if err != nil {
		return err
	}
	err = manager.Get().UserManager().SetUserLevelByLevelSet(levelSets)
	if err != nil {
		return err
	}
	err = manager.Get().LiveRoomManager().SetDoneByCreateAt(timeStr)
	if err != nil {
		return err
	}
	return nil
}

// 处理升级，并送礼物
func DealBackDataByTime(conn *websocket.Conn, liveRoomId string, times int, timestamp int64) error {
	// 处理时间戳，转换成时间字符串
	sec := timestamp / 1000
	nsec := (timestamp % 1000) * 1000000
	// 创建时间对象
	t := time.Unix(sec, nsec)
	// 格式化为字符串
	timeStr := t.Format("2006-01-02 15:04:05")
	fmt.Println(timeStr) // 输出：2021-10-01 12:00:00

	//处理对局数据
	liveTrackUserInfoList, _ := manager.Get().LiveRoomManager().GetLiveTrackInfosWithUserInfoByTime(liveRoomId, times, timeStr)
	for _, info := range liveTrackUserInfoList {
		createTimestamp, hasErr := utils.ConvertNullTimeToMicroTimestamp(info.CreateAt)
		if hasErr {
			createTimestamp = time.Now().UnixMilli()
		}

		// 创建一个礼物事件
		data := models.LiveEventData{
			Event: "broad_join_track",
			Data: struct {
				MsgID         string `json:"msg_id"`         // 事件的ID
				SecOpenID     string `json:"sec_openid"`     // 用户的加密openid
				Type          string `json:"type"`           // 事件类型：comment, gift, like
				Content       string `json:"content"`        // 评论内容（仅评论有效）
				Camp          int    `json:"camp"`           // 评论内容（仅评论有效）
				Job           int    `json:"job"`            // 所属职业
				SecGiftID     string `json:"sec_gift_id"`    // 加密的礼物id（仅礼物有效）
				GiftNum       int    `json:"gift_num"`       // 送出的礼物数量（仅礼物有效）
				GiftValue     int    `json:"gift_value"`     // 礼物总价值，单位分（仅礼物有效）
				Name          string `json:"name"`           // 用户昵称
				Level         int    `json:"level"`          // 用户等级
				AccGiftScore  int    `json:"acc_gift_score"` // 直播间当前用户累计礼物价值
				LikeNum       string `json:"like_num"`       // 点赞数量（仅点赞有效）
				AvatarURL     string `json:"avatar_url"`     // 用户头像
				Nickname      string `json:"nickname"`       // 用户昵称
				UserScore     int    `json:"user_score"`     // 用户积分
				GiftLevel     int    `json:"gift_level"`     // 礼物等级
				GiftUpgrading int    `json:"gift_upgrading"` // 礼物当前次升级
				GameScore     int    `json:"game_score"`     // 游戏当局分数
				Timestamp     int64  `json:"timestamp"`      // 事件时间戳
			}{
				MsgID:     uuid.New().String(),
				SecOpenID: info.UserId,
				Type:      "broad_join_track",
				Content:   strconv.Itoa(info.Track),
				Camp:      info.Track,
				Job:       info.Job,
				SecGiftID: "n1/Dg1905sj1FyoBlQBvmbaDZFBNaKuKZH6zxHkv8Lg5x2cRfrKUTb8gzMs=",
				GiftNum:   2,
				GiftValue: 10,
				Name:      "",
				Nickname:  info.UserName,
				Level:     info.UserLevel,
				AvatarURL: info.UserHeadImg,
				UserScore: info.UserScore,
				Timestamp: createTimestamp,
			},
		}

		// 将ack消息发送给前端
		if err := conn.WriteJSON(data); err != nil {
			fmt.Println("error sending ack message:", err)
		}
	}

	//处理礼物数据
	gameScore, _ := manager.Get().GiftRecordManager().GetTotalScoreByRoomId(liveRoomId, times)

	giftWithUserInfos, _ := manager.Get().GiftRecordManager().GetGiftRecordWithUserInfoByLiveRoomAndTimesByTime(liveRoomId, times, timeStr)
	for i := 0; i < len(giftWithUserInfos); i++ {
		info := giftWithUserInfos[i]

		createTimestamp, hasErr := utils.ConvertNullTimeToMicroTimestamp(info.CreateAt)
		if hasErr {
			createTimestamp = time.Now().UnixMilli()
		}

		accScore, err := manager.Get().GiftRecordManager().GetAccScoreByRoomIdAndUserId(liveRoomId, times, info.UserId)
		if err != nil {
			accScore = info.TotalScore
		}

		// 创建一个礼物事件
		data := models.LiveEventData{
			Event: "broad_live_gift",
			Data: struct {
				MsgID         string `json:"msg_id"`         // 事件的ID
				SecOpenID     string `json:"sec_openid"`     // 用户的加密openid
				Type          string `json:"type"`           // 事件类型：comment, gift, like
				Content       string `json:"content"`        // 评论内容（仅评论有效）
				Camp          int    `json:"camp"`           // 所属阵营
				Job           int    `json:"job"`            // 所属职业
				SecGiftID     string `json:"sec_gift_id"`    // 加密的礼物id（仅礼物有效）
				GiftNum       int    `json:"gift_num"`       // 送出的礼物数量（仅礼物有效）
				GiftValue     int    `json:"gift_value"`     // 礼物总价值，单位分（仅礼物有效）
				Name          string `json:"name"`           // 用户昵称
				Level         int    `json:"level"`          // 用户等级
				AccGiftScore  int    `json:"acc_gift_score"` // 直播间当前用户累计礼物价值
				LikeNum       string `json:"like_num"`       // 点赞数量（仅点赞有效）
				AvatarURL     string `json:"avatar_url"`     // 用户头像
				Nickname      string `json:"nickname"`       // 用户昵称
				UserScore     int    `json:"user_score"`     // 用户积分
				GiftLevel     int    `json:"gift_level"`     // 礼物等级
				GiftUpgrading int    `json:"gift_upgrading"` // 礼物当前次升级
				GameScore     int    `json:"game_score"`     // 游戏当局分数
				Timestamp     int64  `json:"timestamp"`      // 事件时间戳
			}{
				MsgID:         uuid.New().String(),
				SecOpenID:     info.UserId,
				Type:          "live_gift",
				Camp:          info.Track,
				SecGiftID:     info.GiftId,
				GiftNum:       info.Amount,
				GiftValue:     info.TotalValue,
				Name:          info.GiftName,
				Nickname:      info.UserName,
				Level:         info.UserLevel,
				AccGiftScore:  accScore,
				AvatarURL:     info.UserHeadImg,
				UserScore:     info.UserScore,
				GiftLevel:     info.GiftLevel,
				GiftUpgrading: info.GiftUpgrading,
				GameScore:     gameScore,
				Timestamp:     createTimestamp,
			},
		}

		// 将ack消息发送给前端
		if err := conn.WriteJSON(data); err != nil {
			fmt.Println("error sending ack message:", err)
		}
	}

	return nil
}
